﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Read.Api.Application.Command.Product;
using Provenance.Read.Api.Dto.Product;

namespace Provenance.Read.Api.Application.CommandHandler.Product
{
    public class GetProductListCommandHandler : IRequestHandler<GetProductListCommand, ApiResult<IList<GetProductListResponseDTO>>>
    {
        private readonly IProductRepository _productRepository;
        private readonly ILogger<GetProductListCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetProductListCommandHandler(IProductRepository productRepository, ILogger<GetProductListCommandHandler> logger, IMapper mapper)
        {
            _productRepository = productRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<IList<GetProductListResponseDTO>>> Handle(GetProductListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await _productRepository.GetAllAsync(x => x.IsDeleted == false);
                var response = _mapper.Map<IList<GetProductListResponseDTO>>(list);
                return ApiResult<IList<GetProductListResponseDTO>>.Success(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting product list"+ex.Message);
                return ApiResult<IList<GetProductListResponseDTO>>.Failure("Error getting product list"+ex.Message);
            }
        }
    }
}
